package tuling.netty.splitpacket.encoding;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import tuling.netty.splitpacket.domain.RgsMessageProtocol;

import java.util.List;

/**
 * @author RenGaoshuai
 * @date 2023/12/4 14:53
 * @description 自定义解码器
 * <p>
 * 将netty底层交互的bytebuf转成想要的信息
 */
public class RgsCustomizeDecode extends ByteToMessageDecoder {

    int length = 0;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        System.out.println("自定义编码器的 decode 方法被调用");

        if (byteBuf.readableBytes() >= 4) {
            if (length == 0) {
                //先把长度读出来
                length = byteBuf.readInt();
            }

            //数据还不够
            if (byteBuf.readableBytes() < length) {
                System.out.println("当前可读数据不够，继续等待。。");
                return;
            }

            byte[] content = new byte[length];
            if (byteBuf.readableBytes() >= length) {
                byteBuf.readBytes(content);

                out.add(new RgsMessageProtocol(length, content));
            }
            length = 0;
        }
    }
}
